// Learn TypeScript:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/life-cycle-callbacks.html

const {ccclass, property} = cc._decorator;

@ccclass
export default class star extends cc.Component {

    @property(cc.Label)
    label: cc.Label = null;

    @property
    text: string = 'hello';

    @property
    pickRadius = 65;

    //displayName: "Score (player)",
    //tooltip: "The score of player",
    // @property({
    //     displayName: "game node", type: cc.Node
    //  })
    // game: cc.Node = null
    game = null
    // LIFE-CYCLE CALLBACKS:

    // 
    onLoad () {

    }

    init (game) {
        this.game = game
    }

    start () {

    }

    getPlayerDistance() {
        // 根据 Player 节点位置判断距离
        let gameObj = this.game;
        var playerPos = gameObj.player.getPosition();
        //var playerPos = gameObj.getComponent('player').getPosition();
        // 根据两点位置计算两点之间距离
        var dist = this.node.position.sub(playerPos).mag();
        return dist;
    }

    onPicked() {
        // 当星星被收集时，调用 Game 脚本中的接口，生成一个新的星星
        this.game.getComponent('game').spawnNewStar();
          // 调用 Game 脚本的得分方法
        this.game.gainScore();
        // 然后销毁当前星星节点
        this.node.destroy();
    }
    // update (dt) {}
    update(dt) {
        // 每帧判断星星和主角之间的距离是否小于收集距离
        let _distance = this.getPlayerDistance();
         if (_distance < this.pickRadius) {
             // 调用收集行为
             this.onPicked();
            return;
         }

        // 根据 Game 脚本中的计时器更新星星的透明度
        var opacityRatio = 1 - this.game.timer/this.game.starDuration;
        var minOpacity = 50;
        this.node.opacity = minOpacity + Math.floor(opacityRatio * (255 - minOpacity));
    }
}
